package koalacam.server;


import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;


/**
 * 登录
 * @author Wangshutao
 * 2016年7月4日
 */
public class Auth {
	
	/**
	 * 登录 返回 Cookie值
	 * @param url API地址
	 * @param username 账号
	 * @param password 密码
	 * @return cookie cookie值
	 * @throws Exception 
	 */
	public static CookieStore login(String url,String username,String password) throws Exception {
        System.out.println("Start POST /auth/login 登录 ...");
        
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost request = new HttpPost(url);
        
        //设置User-Agent、Content-Type
        request.setHeader("User-Agent", "Koala Admin");
        request.setHeader("Content-Type", "application/json");
        
        JSONObject json = new JSONObject();
        json.put("username", username);
        json.put("password", password);
        request.setEntity(new StringEntity(json.toString(), "UTF-8"));

        //发起网络请求 获取返回信息
        HttpClientContext context = HttpClientContext.create();
        CloseableHttpResponse response = httpclient.execute(request, context);
        String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
        
        //解析JSON数据
        JSONObject resp = new JSONObject(responseBody);
        int result = resp.optInt("code", -1);
        if (result != 0) {
            System.err.println("Login failed, code:" + result);
        }else{
        	System.out.println("Login Success,id:" + resp.getJSONObject("data").getInt("id"));
        	return  context.getCookieStore();
        }
        return null;
    }

}
